package com.ouran.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.imageio.ImageIO;

import sun.misc.BASE64Encoder;

public class ImageUtil {

	private static BASE64Encoder encoder = new sun.misc.BASE64Encoder();

	/**
	 * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	 * 
	 * @param imgFilePath
	 * @return
	 */
	public static String GetImageStr(String imgFilePath) {

		try {
			// 创建URL
			URL url = new URL(imgFilePath);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);

			// 对字节数组Base64编码
			return convertImageStreamToByte(conn.getInputStream(), "jpg");

		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";

	}

	/**
	 * 将图片流转换为BASE64加密字符串.
	 * 
	 * @param imageInputStream
	 * @param format 图片格式.
	 * @return
	 */
	public static String convertImageStreamToByte(InputStream imageInputStream, String format) {
		BufferedImage bi = null;
		ByteArrayOutputStream baos = null;
		String result = null;
		try {
			bi = ImageIO.read(imageInputStream);
			baos = new ByteArrayOutputStream();
			ImageIO.write(bi, format == null ? "jpg" : format, baos);
			byte[] bytes = baos.toByteArray();
			result = encoder.encodeBuffer(bytes).trim();
		} catch (IOException e) {
			System.out.println("将图片流转换为 BASE64加密字符串失败: " + e);
		} finally {
			try {
				if (baos != null) {
					baos.close();
					baos = null;
				}
			} catch (Exception e) {
				System.out.println("关闭文件流发生异常: " + e);
			}
		}
		return result;
	}

}
